package com.changyi.device.printer;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.device.Printer;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.ReqeustException;
import com.landicorp.android.eptapi.exception.RequestException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;
import com.landicorp.android.eptapi.utils.QrCode;
import com.landicorp.android.eptapi.device.Printer.Format;
import com.sunmi.peripheral.printer.SunmiPrinterService;

import java.util.List;

/**
 * Created by xin on 2021/3/26
 * desc:
 */
public class LandiA8Printer implements PrinterInterface {
    private Context mContext;
    private static LandiA8Printer mLandiA8Printer;

    private LandiA8Printer(Context context) {
        mContext = context;
    }

    public static LandiA8Printer getInstance(Context context) {
        if (mLandiA8Printer == null) {
            synchronized (LandiA8Printer.class){
                if (mLandiA8Printer == null) {
                    mLandiA8Printer = new LandiA8Printer(context);
                }
            }
        }
        return mLandiA8Printer;
    }

    /**
     * 初始化打印机
     */
    @Override
    public PrinterInterface initDevice() {
        try {
            DeviceService.login(mContext);
        } catch (ServiceOccupiedException e) {
            e.printStackTrace();
        } catch (ReloginException e) {
            e.printStackTrace();
        } catch (UnsupportMultiProcess unsupportMultiProcess) {
            unsupportMultiProcess.printStackTrace();
        } catch (RequestException e) {
            e.printStackTrace();
        }
        return mLandiA8Printer;
    }

    /**
     * 打印标题头
     * @param title
     * @return
     */
    @Override
    public LandiA8Printer printTitle(final String title) {
        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                            Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();

                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    // 默认是实模式,此处设置为虚模式
                    printer.setMode(Printer.MODE_REAL);
                    Printer.Format format = new Printer.Format();
                    format.setAscSize(Printer.Format.ASC_DOT5x7);
                    format.setHzScale(Format.HZ_SC1x2);
                    printer.setFormat(format);
                    printer.printText(title);
                    printer.feedLine(1);
                }
            }.start();

        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;
    }

    /**
     * 打印字符串
     * @param text
     * @return
     */
    @Override
    public LandiA8Printer printText(final String text) {

        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                            Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:

                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    // 默认是实模式,此处设置为虚模式
                    printer.setMode(Printer.MODE_REAL);
                    Printer.Format format = new Printer.Format();
                    format.setAscSize(Printer.Format.ASC_DOT5x7);
                    format.setHzScale(Printer.Format.HZ_SC1x1);
                    printer.setFormat(format);
                    printer.printText(text);
                }

            }.start();

        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;
    }

    /**
     * 打印字符串列表
     * @param mList
     * @return
     */
    @Override
    public LandiA8Printer printList(final List<String> mList) {
        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                            Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    // 默认是实模式,此处设置为虚模式
                    printer.setMode(Printer.MODE_REAL);
                    Printer.Format format = new Printer.Format();
                    format.setAscSize(Format.ASC_DOT5x7);
                    format.setHzScale(Format.HZ_SC1x1);
                    printer.setFormat(format);

                    for (String content : mList) {
                        if(content.contains("|")){
                            printer.feedLine(1);  // 空行

                            String[] aa = content.split("\\|");
                            for (int i = 0 ; i <aa.length ; i++ ) {
                                printer.printText(aa[i]+"\n");
                            }
                        }else  if (content.contains("@@@")){
                            String temp = content.substring(3,content.length());
                            printer.feedLine(1);  // 空行
                            printer.printQrCode(100,new QrCode(temp, QrCode.ECLEVEL_M),180);

                        } else  if (content.contains("&&&")){
                            String temp = content.substring(3,content.length());
                            printer.feedLine(1);  // 空行
                            printer.printBarCode(temp);
                        }  else{
                            printer.printText(content.trim()+"\n");
                        }
                    }
                }
            }.start();
           feedLine(3);
        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;
    }

    /**
     * 打印一维码
     * @param code
     * @return
     */
    @Override
    public LandiA8Printer printCode(final String code) {
        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                            Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    // 默认是实模式,此处设置为虚模式
                    printer.setMode(Printer.MODE_REAL);
                    Format format = new Format();
                    format.setAscSize(Format.ASC_DOT5x7);
                    format.setHzScale(Format.HZ_SC1x1);
                    printer.setFormat(format);
                    printer.printBarCode(70, -1, code );
                }
            }.start();

        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;
    }

    /**
     * 打印二维码
     * @param qRCode
     * @return
     */
    @Override
    public LandiA8Printer printQrCode(final String qRCode) {
        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                              Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    Format format = new Format();
                    printer.setMode(Printer.MODE_REAL);
                    format.setAscSize(Printer.Format.ASC_DOT5x7);
                    format.setHzScale(Printer.Format.HZ_SC1x1);
                    printer.setFormat(format);
                    printer.printQrCode(100,new QrCode(qRCode,QrCode.ECLEVEL_M),180);
                }
            }.start();

        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;
    }

    /**
     * 走纸
     * @param feelLine
     * @return
     */
    @Override
    public LandiA8Printer feedLine(final int feelLine) {
        try {
            new Printer.Progress() {
                @Override
                public void onCrash() {
                    onServiceException();
                }

                @Override
                public void onFinish(int code) {
                    switch (code) {
                        case Printer.ERROR_NONE:
                            Toast.makeText(mContext, "打印结束 打印成功!", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(mContext, "打印失败! 错误代码 : " + code + " ["
                                    + getErrorDescription(code) + "]", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void doPrint(Printer printer)
                        throws Exception {
                    // 默认是实模式,此处设置为虚模式
                    printer.setMode(Printer.MODE_REAL);
                    Format format = new Format();
                    format.setAscSize(Format.ASC_DOT5x7);
                    format.setHzScale(Format.HZ_SC1x1);
                    printer.setFormat(format);
                    printer.feedLine(feelLine);
                }

            }.start();

        } catch (ReqeustException e) {
            e.printStackTrace();
            onServiceException();
        }
        return mLandiA8Printer;

    }

    /**
     * 服务异常处理
     */
    private void onServiceException() {
        Toast.makeText(mContext, "设备服务异常，正在重启，请稍后重试!", Toast.LENGTH_SHORT).show();
        initDevice();
    }

    private String getErrorDescription(int code) {
        switch (code) {
            // case Printer.STATE_OK: return "正常状态，无错误";
            // case Printer.ERROR_NONE: return "正常状态，无错误";
            case Printer.ERROR_PAPERENDED:
                return "缺纸，不能打印";
            case Printer.ERROR_HARDERR:
                return "硬件错误";
            case Printer.ERROR_OVERHEAT:
                return "打印头过热";
            case Printer.ERROR_BUFOVERFLOW:
                return "缓冲模式下所操作的位置超出范围";
            case Printer.ERROR_LOWVOL:
                return "低压保护";
            case Printer.ERROR_PAPERENDING:
                return "纸张将要用尽，还允许打印*(单步进针打特有返回值)";
            case Printer.ERROR_MOTORERR:
                return "打印机芯故障(过快或者过慢)";
            case Printer.ERROR_PENOFOUND:
                return "自动定位没有找到对齐位置,纸张回到原来位置";
            case Printer.ERROR_PAPERJAM:
                return "卡纸";
            case Printer.ERROR_NOBM:
                return "没有找到黑标";
            case Printer.ERROR_BUSY:
                return "打印机处于忙状态";
            case Printer.ERROR_BMBLACK:
                return "黑标探测器检测到黑色信号";
            case Printer.ERROR_WORKON:
                return "打印机电源处于打开状态";
            case Printer.ERROR_LIFTHEAD:
                return "打印头抬起*(自助热敏打印机特有返回值)";
            case Printer.ERROR_LOWTEMP:
                return "低温保护或AD出错*(自助热敏打印机特有返回值)";
        }
        return "未知错误";
    }

    /**
     * 释放打印机
     */
    public void Logout(){
        DeviceService.logout();
    }

}
